//
//  CalculatorEngine.swift
//  Calculator
//
//  Created by 左忠飞 on 2021/1/17.
//  Copyright © 2021 左忠飞. All rights reserved.
//

import UIKit

class CalculatorEngine: NSObject {

    //运算符集合
    let funcArray:CharacterSet = ["+","-","*","/","%","^"]

    
    func calculatEquation(equation:String) -> Double {
        //以运算符进行分割,获取到所有数字
        let elementArray = equation.components(separatedBy: funcArray)
        //设置一个运算标记游标
        var tip = 0
        //运算结果
        var result:Double = Double(elementArray[0])!
        //遍历运算表达式
        for char in equation {
            switch char {
            case "+":
                tip += 1
                if elementArray.count > tip {
                    result += Double(elementArray[tip])!
                }
            case "-":
                tip += 1
                if elementArray.count > tip {
                    result -= Double(elementArray[tip])!
                }
            case "*":
                tip += 1
                if elementArray.count > tip {
                    result *= Double(elementArray[tip])!
                }
            case "/":
                tip += 1
                if elementArray.count > tip {
                    result /= Double(elementArray[tip])!
                }
            case "%":
                tip += 1
                if elementArray.count > tip {
                    result += Double(Int(result)%Int(elementArray[tip])!)
                }
            case "^":
                tip += 1
                if elementArray.count > tip {
                    let tmp = result
                    for _ in 1..<Int(elementArray[tip])! {
                        result *= tmp
                    }
                }
            default: break
                
            }
        }
        
        
        return result
    }
}
